//
//  PersonMessageViewController.m
//  Sports-Go
//
//  Created by rimi on 16/9/20.
//  Copyright © 2016年 YRL. All rights reserved.
//

#import "PersonMessageViewController.h"
#import "PersonMessageCell.h"
#import "UIButton+WebCache.h"
#import "CustomAlertView.h"
#import "YJPickerView.h"
//获取屏幕设度，高度
#define kScreenHight [UIScreen mainScreen].bounds.size.height
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define headViewH    kScreenWidth/3*2
#define headH        kScreenWidth/4

@interface PersonMessageViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSArray *dataSource;
@property (nonatomic,strong) PersonMessageCell *cell;
@property (nonatomic,strong) UIImageView *headButton;
@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic,strong) NSMutableDictionary *userInfoDic;//保存的数据
@property (nonatomic,strong) NSMutableDictionary *userDic;//取出来的数据
@property (nonatomic,assign)CGFloat scale;


@end

@implementation PersonMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _userInfoDic = [NSMutableDictionary dictionary];
    _userDic = [NSMutableDictionary dictionary];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"编辑个人资料";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveTheMessage)];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    //去掉导航栏返回字
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:17],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.barTintColor = getColor(58, 206, 248, 1);

    [self.view addSubview:self.tableView];
    _dataSource = @[@[@"昵称",@"性别",@"年龄",@"兴趣",@"个性签名"],@[@"身高",@"体重"]];
    NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
     NSDictionary *headImageDic =  [[NSUserDefaults standardUserDefaults]objectForKey:@"userInfo"];//第三方登陆的信息
    AVQuery *query = [AVQuery queryWithClassName:@"userInfo"];//取表
    [query whereKey:@"userName" equalTo:userName];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        _userDic = [objects.lastObject[@"data"] mutableCopy];
        
        if (_userDic) {//修改资料保存的头像
            if (_userDic[@"headImage"]) {
                 [_headButton sd_setImageWithURL:[NSURL URLWithString:_userDic[@"headImage"]]];
            }else{
              _headButton.image =  [UIImage imageNamed:@"游客2"] ;
            }
        }else if (headImageDic){
            //没有修改资料,第三方登陆,获取用户头像
            if (headImageDic[@"icon"]) {
                [_headButton sd_setImageWithURL:[NSURL URLWithString:headImageDic[@"icon"]]];
            }else{
                //第三方登陆头像不存在
                _headButton.image =  [UIImage imageNamed:@"游客2"] ;
            }
        }
        else{
            //没有头像是赋值一个默认头像
            _headButton.image =  [UIImage imageNamed:@"游客2"] ;
        }
        
    }];

    self.tableView.contentInset = UIEdgeInsetsMake(headViewH, 0, 0, 0);
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -headViewH, kScreenWidth, headViewH)];

    _headButton = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, headH, headH)];
    self.scale = _imageView.bounds.size.width/_imageView.bounds.size.height;
     _headButton.center = _imageView.center;
    _headButton.layer.cornerRadius = headH/2;
    _headButton.layer.masksToBounds = YES;
     _headButton.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(chooseTheHeadImage)];
    [_headButton addGestureRecognizer:tap];
    
    _imageView.image = [UIImage imageNamed:@"myBack"];
    
    [self.tableView addSubview:_imageView];
    [self.tableView addSubview:_headButton];
}
- (void)chooseTheHeadImage{
    //选取头像
    
    UIAlertController *alter = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *alter1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self chooseType:3];
    }];
    
    UIAlertAction *alter2 = [UIAlertAction actionWithTitle:@"从相册读取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self chooseType:1];
    }];
    UIAlertAction *alter3 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self chooseType:2];
    }];
    [alter addAction:alter2];
    [alter addAction:alter3];
    [alter addAction:alter1];
    
    [self presentViewController:alter animated:YES completion:nil];
    
}
- (void)chooseType:(NSInteger)type{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    
    picker.delegate = self;
    
    picker.allowsEditing = YES;
    
    if (type == 1) {
        picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        [self presentViewController:picker animated:YES completion:nil];
        
    }else if (type == 2){
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:picker animated:YES completion:nil];
    }else{
        
    }
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
   
    _headButton.image = info[@"UIImagePickerControllerEditedImage"];
    UIImage *image = info[@"UIImagePickerControllerEditedImage"];
    NSData *data = UIImageJPEGRepresentation(image, 0.5);
     AVFile *file = [AVFile fileWithName:@"1.png" data:data];
    
    [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {

        [[NSUserDefaults standardUserDefaults] setObject:file.url forKey:@"headImageUrl"];
        [self saveTheMessage];
    }];
    
    
    [self dismissViewControllerAnimated:YES completion:nil];

}

#pragma mark -- leftBarButtonItem click
- (void)saveTheMessage{
  
    [self saveTheCellMessage];
    if (_userInfoDic) {
        NSMutableDictionary *dic = _userInfoDic.mutableCopy;
        NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
        if (userName) {
            
            AVObject *userObject = [AVObject objectWithClassName:@"userInfo"];//建一张表
            if ([[NSUserDefaults standardUserDefaults] objectForKey:@"headImageUrl"]) {
                [dic setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"headImageUrl"] forKey:@"headImage"];
            }
            [userObject setObject:userName forKey:@"userName"];
            [userObject setObject:dic forKey:@"data"];
            [userObject saveInBackground];
            
            [self warnWitherrorInfo:@"保存成功"];
        }
        
    }else{
        NSLog(@"info   null");
    }
}
#pragma mark -- alter
- (void)warnWitherrorInfo:(NSString *)error{
    //警示框
    UILabel *label = [[UILabel alloc]initWithFrame:RzCGRectMake(90, 250, 185, 50)];
    label.backgroundColor = getColor(193, 162, 151, 1);
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:16];
    label.numberOfLines = 0;
    label.text = error;
    label.layer.cornerRadius = 5;
    label.layer.masksToBounds = YES;
    label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:label];
    [UIView animateWithDuration:2.0 animations:^{
        label.alpha = 0.0;
    } completion:^(BOOL finished) {
        
        [label removeFromSuperview];
    }];
    
    
}

#pragma mark -- tableview delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return _dataSource.count;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    NSArray *array = _dataSource[section];
    return array.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 1) {
        return 0.000001;
    }
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{

    UIView *footerView = [[UIView alloc] initWithFrame:RzCGRectMake(0, 0, 375, 10)];
    footerView.backgroundColor = getColor(236, 236, 236, 1);
    if (section == 1) {
        return nil;
    }
    return footerView;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  
    _cell = [tableView dequeueReusableCellWithIdentifier:@"personalCell"];
    _cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSArray *arr = _dataSource[indexPath.section];
    _cell.titleLabel.text = arr[indexPath.row];
    
    _cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    if (indexPath.section == 0) {
        if (_userDic) {
            if (indexPath.row == 0) {
                if ([_userDic[@"nickName"] length] > 0) {
                    _cell.resultLabel.text = _userDic[@"nickName"];
                }
            }
            if (indexPath.row == 1) {
                if ([_userDic[@"sex"] length] > 0) {
                    _cell.resultLabel.text = _userDic[@"sex"];
                }
            }
            if (indexPath.row == 2) {
                if ([_userDic[@"age"] length] > 0) {
                    _cell.resultLabel.text = _userDic[@"age"];
                }
            }
            if (indexPath.row == 3) {
                if ([_userDic[@"hobby"] length] > 0) {
                    _cell.resultLabel.text = _userDic[@"hobby"];
                }
            }
            if (indexPath.row == 4) {
                if ([_userDic[@"sign"] length] > 0) {
                    _cell.resultLabel.text = _userDic[@"sign"];
                }
            }

        }
        _cell.resultLabel.tag = 100 + indexPath.row;
    }else{
        if (_userDic) {
            
            
            if (indexPath.row == 0) {
                if ([_userDic[@"height"] length] > 0) {
                    _cell.resultLabel.text = _userDic[@"height"];
                }
            }
            if (indexPath.row == 1) {
                if ([_userDic[@"weight"] length] > 0) {
                    _cell.resultLabel.text = _userDic[@"weight"];
                }
            }
        }
        _cell.resultLabel.tag = 105 + indexPath.row;
    }
    return _cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            UIView *view1 = [[UIView alloc] init];
            view1.backgroundColor = [UIColor whiteColor];
            UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(5, 0, 260, 40)];
            field.clearButtonMode = UITextFieldViewModeWhileEditing;
            field.backgroundColor = [UIColor whiteColor];
            field.layer.borderWidth = 1;
            field.layer.borderColor = [UIColor colorWithRed:58/255.0 green:206/255.0  blue:248/255.0  alpha:1].CGColor;
            [view1 addSubview:field];
       [CustomAlertView popViewWithTitle:@"请输入您的昵称" contentText:view1 contentFrame:CGRectMake(10, 30, 270, 40) bottomView:nil bottomFrame:CGRectMake(10, 10, 270, 100) leftButtonTitle:@"取消" rightButtonTitle:@"确定" leftBlock:^{
                                  
        } rightBlock:^{
            
            UILabel *lab = [self.view viewWithTag:100];
            lab.text = field.text;
           
            
        } dismissBlock:^{
                                  
        }];
            
        }
        if (indexPath.row == 1) {
            NSArray * str  = @[@"男",@"女"];
            YJPickerView *pickerView = [YJPickerView YJPickerStringPickerWithTitle:str andHeadTitle:@"性别选择" Andcall:^(YJPickerView *pickerView, NSString *choiceString) {
                UILabel *lab = [self.view viewWithTag:101];
                lab.text = choiceString;
                
                [pickerView dismissPicker];
            }];
           
            [pickerView show];

        }
        if (indexPath.row == 2) {
            //年龄
            
            NSMutableArray *str1 = [NSMutableArray array];
            for (int i = 5; i < 100; i ++) {
                
                NSString *number = [NSString stringWithFormat:@"%d",i];
                [str1 addObject:number];
                
            }
            YJPickerView *pickerView = [YJPickerView YJPickerStringPickerWithTitle:str1 andHeadTitle:@"年龄选择" Andcall:^(YJPickerView *pickerView, NSString *choiceString) {
               
                UILabel *lab = [self.view viewWithTag:102];
                lab.text = choiceString;
                [pickerView dismissPicker];
                }];
            
            [pickerView show];
            
        }
        if (indexPath.row == 3) {
            //兴趣
            UIView *view1 = [[UIView alloc] init];
            view1.backgroundColor = [UIColor whiteColor];
            UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(5, 0, 260, 40)];
            field.clearButtonMode = UITextFieldViewModeWhileEditing;
            field.backgroundColor = [UIColor whiteColor];
            field.layer.borderWidth = 1;
            field.layer.borderColor = [UIColor colorWithRed:58/255.0 green:206/255.0  blue:248/255.0  alpha:1].CGColor;
            [view1 addSubview:field];
            [CustomAlertView popViewWithTitle:@"请输入您的兴趣" contentText:view1 contentFrame:CGRectMake(10, 30, 270, 40) bottomView:nil bottomFrame:CGRectMake(10, 10, 270, 100) leftButtonTitle:@"取消" rightButtonTitle:@"确定" leftBlock:^{
                
            } rightBlock:^{
                
                
                UILabel *lab = [self.view viewWithTag:103];
                lab.text = field.text;
               

            } dismissBlock:^{
                
            }];
        
        }
        if (indexPath.row == 4) {
            //个性签名
            UIView *view1 = [[UIView alloc] init];
            view1.backgroundColor = [UIColor whiteColor];
            UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(5, 0, 260, 40)];
            field.clearButtonMode = UITextFieldViewModeWhileEditing;
            field.backgroundColor = [UIColor whiteColor];
            field.layer.borderWidth = 1;
            field.layer.borderColor = [UIColor colorWithRed:58/255.0 green:206/255.0  blue:248/255.0  alpha:1].CGColor;
            [view1 addSubview:field];
            [CustomAlertView popViewWithTitle:@"请输入您的个性签名" contentText:view1 contentFrame:CGRectMake(10, 30, 270, 40) bottomView:nil bottomFrame:CGRectMake(10, 10, 270, 100) leftButtonTitle:@"取消" rightButtonTitle:@"确定" leftBlock:^{
                
            } rightBlock:^{
                UILabel *lab = [self.view viewWithTag:104];
                lab.text = field.text;
                
            } dismissBlock:^{
                
            }];
        
        }
        
    }else{
        if (indexPath.row == 0) {
            NSMutableArray *str1 = [NSMutableArray array];
            for (int i = 50; i < 220; i ++) {
                
                NSString *number = [NSString stringWithFormat:@"%d",i];
                [str1 addObject:number];
  
            }
           
        YJPickerView *pickerView = [YJPickerView YJPickerStringPickerWithTitle:str1 andHeadTitle:@"身高选择(cm)" Andcall:^(YJPickerView *pickerView, NSString *choiceString) {
            
            UILabel *lab = [self.view viewWithTag:105];
            lab.text = [NSString stringWithFormat:@"%@cm",choiceString];
            
                [pickerView dismissPicker];
            }];
            
            [pickerView show];

        }else{
            NSMutableArray *str = [NSMutableArray array];
            for (int i = 30; i < 100; i ++) {
                NSString *number = [NSString stringWithFormat:@"%d",i];
                [str addObject:number];
            }
            YJPickerView *pickerView = [YJPickerView YJPickerStringPickerWithTitle:str andHeadTitle:@"体重选择(kg)" Andcall:^(YJPickerView *pickerView, NSString *choiceString) {
                
                UILabel *lab = [self.view viewWithTag:106];
                lab.text = [NSString stringWithFormat:@"%@kg",choiceString];

                [pickerView dismissPicker];
            }];
            
            [pickerView show];
        }
    }
   
    [self saveTheCellMessage];
    [self.tableView reloadData];
}

- (void)saveTheCellMessage{
    
     UILabel *label = [self.view viewWithTag:100];
     [_userInfoDic setValue:label.text forKey:@"nickName"];
     UILabel *label1 = [self.view viewWithTag:101];
     [_userInfoDic setValue:label1.text forKey:@"sex"];
     UILabel *label2 = [self.view viewWithTag:102];
     [_userInfoDic setValue:label2.text forKey:@"age"];
     UILabel *label3 = [self.view viewWithTag:103];
     [_userInfoDic setValue:label3.text forKey:@"hobby"];
    
     UILabel *label4 = [self.view viewWithTag:104];
     [_userInfoDic setValue:label4.text forKey:@"sign"];
    
     UILabel *label5 = [self.view viewWithTag:105];
     [_userInfoDic setValue:label5.text forKey:@"height"];
    
     UILabel *label6 = [self.view viewWithTag:106];
     [_userInfoDic setValue:label6.text forKey:@"weight"];
    
    
    _userDic = _userInfoDic;
    

}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offsetY = scrollView.contentOffset.y;
    
    if (scrollView.contentOffset.y < -headViewH ) {
        // 高度宽度同时拉伸 从中心放大
        self.imageView.frame = CGRectMake(0, offsetY, kScreenWidth, -offsetY);
        CGFloat conY = scrollView.contentOffset.y  + headViewH;
       CGFloat imgH = -(offsetY);
        CGFloat imgW = imgH * self.scale;
        self.imageView.frame = CGRectMake(-(imgW - kScreenWidth)/2,offsetY, imgW,imgH);
        
        _headButton.frame =CGRectMake(0, 0, headH-conY, headH-conY);
        _headButton.center =self.imageView.center;
        _headButton.layer.cornerRadius = _headButton.bounds.size.height/2;
        
    }
    //NSLog(@"%0.0f",scrollView.contentOffset.y);
}


#pragma mark -- lazy
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:RzCGRectMake(0, 0, 375, 667) style:UITableViewStyleGrouped];
        _tableView.rowHeight = 70;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.backgroundColor = [UIColor whiteColor];
        [_tableView registerClass:[PersonMessageCell class] forCellReuseIdentifier:@"personalCell"];
        
    }
    return _tableView;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   
    
    NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
    AVQuery *query = [AVQuery queryWithClassName:@"userInfo"];//取表
    [query whereKey:@"userName" equalTo:userName];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
     _userDic = [objects.lastObject[@"data"] mutableCopy];
        
       [self.tableView reloadData];
    }];
    
    
    [self.navigationController setNavigationBarHidden:NO];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{

    [super viewWillDisappear:animated];
    
    
    [self.navigationController setNavigationBarHidden:YES];
     self.tabBarController.tabBar.hidden = NO;
}



@end
